# # conftest.py
import os
import re
import shutil
import pathlib
import pytest

from common.logger_ctrl import mylogger
from base_public.get_sys_hw_info import SystemHwInfo
from setting import DTK_PATH, TMP_DIR, EXE_DIR, CPP_DIR
glo_case_cnt = 0  # 用于全局执行用例个数计数

@pytest.hookimpl(hookwrapper=True)  # 添加这个钩子函数来捕获测试结果
def pytest_runtest_makereport(item, call):
    """捕获测试结果并将其附加到item上"""
    outcome = yield
    report = outcome.get_result()

    # 将每个阶段的报告（setup/call/teardown）都存储到item中
    setattr(item, f"rep_{report.when}", report)

@pytest.fixture(scope="session")
def dcu_info():
    """Session级fixture，所有测试用例共享GPU信息"""
    sys_info = SystemHwInfo()
    dcu_info = sys_info.get_dcu_info()
    return dcu_info

@pytest.fixture(scope="function")
def test_env(request):
    """为每个测试用例创建独立目录，并根据结果清理"""
    global glo_case_cnt
    glo_case_cnt += 1
    mylogger.debug(f"[Setup] Start executing testcase {glo_case_cnt}.")
    # 生成唯一目录名（基于测试用例名称）
    test_name = request.node.name
    test_dir = pathlib.Path(f"{TMP_DIR}/{glo_case_cnt}-{test_name}").absolute()

    # 前置操作：创建目录
    test_dir.mkdir(parents=True, exist_ok=True)
    mylogger.debug(f"[Setup] Create a working directory for test cases：{test_dir}")

    os.chdir(test_dir)
    mylogger.debug(f"[Setup] Set the current working directory to '{pathlib.Path.cwd()}'")

    # 将目录传递给测试用例
    yield test_dir

    # mylogger.debug(f"dir(request.node):\n{dir(request.node)}")
    mylogger.debug(f"[Teardown] The output file generated under the working directory({test_dir})：\n{os.listdir(test_dir)}")
    if request.node.rep_call.passed:
        os.chdir("..")
        shutil.rmtree(test_dir, ignore_errors=True)
        mylogger.info(f"[Teardown] Test passed,\n then clean up the test directory：'{test_dir}'")
    # else:
    #     # 测试失败，保留目录
    #     mylogger.info(f"[Teardown] Keep the failed use case directory：'{test_dir}'")
    mylogger.debug(f"[Teardown] End execution testcase {glo_case_cnt}.")
